package com.admin.education.services.Implements;

import com.admin.education.common.utils.StringUtil;
import com.admin.education.dataTransferObject.weChat.Response.WeChatLoginResponse;
import com.admin.education.dataTransferObject.wx.WXTransfer;
import com.admin.education.models.QUser;
import com.admin.education.models.User;
import com.admin.education.repositories.UserInformationRepository;
import com.admin.education.repositories.UserRepository;
import com.admin.education.services.Interfaces.IWeChatService;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.transaction.Transactional;

@Service
@Transactional
@Validated
public class WeChatService implements IWeChatService {
    @Autowired
    private UserInformationRepository userInformationRepository;
    @Autowired
    private UserRepository userRepository;
    private QUser qUser;
    public  WeChatService(){
        qUser = QUser.user;
    }
    @Override
    public WeChatLoginResponse LoginByWeChat(WXTransfer wxTransfer) {
        WeChatLoginResponse weChatLoginResponse =new WeChatLoginResponse();

        JPAQuery<User> userJPAQuery =this.userRepository.selectFrom(qUser).where(qUser.openId.eq(wxTransfer.getOpenId()));

        User user =null;
        if(0!=userJPAQuery.fetchCount()){
            user =userJPAQuery.fetchOne();
            user.setSessionKey(wxTransfer.getSessionKey());
            user.setUnionId(wxTransfer.getUnionId());
            user.setOpenId(wxTransfer.getOpenId());

        }
        else{
            user = new User();
            user.setUnionId(wxTransfer.getUnionId());
            user.setSessionKey(wxTransfer.getSessionKey());
            user.setOpenId(wxTransfer.getOpenId());

            user.setUserName(StringUtil.randomString(24));
            user.setPassword("123456");

            this.userRepository.persist(user);
        }

        weChatLoginResponse.setUserName(user.getUserName());
        weChatLoginResponse.setUserId(user.getId());

        weChatLoginResponse.setSuccess(true);
        return weChatLoginResponse;
    }
}
